﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Sketch.Util
{
    public class ImageUtil
    {
        public static Image Resize(Image imgToResize, Size size, bool allowIncrease = false)
        {
            var sourceWidth = imgToResize.Width;
            var sourceHeight = imgToResize.Height;

            var nPercentW = (size.Width / (float)sourceWidth);
            var nPercentH = (size.Height / (float)sourceHeight);

            var nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;

            if (nPercent > 1.0 && !allowIncrease)
                return imgToResize;

            var destWidth = (int)(sourceWidth * nPercent);
            var destHeight = (int)(sourceHeight * nPercent);

            var b = new Bitmap(destWidth, destHeight);
            using (var g = Graphics.FromImage(b))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            }

            return b;
        }

        public static Image PasteOnCavas(Image image, Size canvasSize)
        {
            var canvas = new Bitmap(width: canvasSize.Width, height: canvasSize.Height);
            
            using (var g = Graphics.FromImage(canvas))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(image, (canvas.Width - image.Width) / 2, (canvas.Height - image.Height) / 2, image.Width, image.Height);
            }
            return canvas;
        }

        public static Image CropTransparentEdges(Image image)
        {
            var min = new Point(int.MaxValue, int.MaxValue);
            var max = new Point(int.MinValue, int.MinValue);

            using (var b = new Bitmap(image))
            {
                for (var x = 0; x < image.Width; ++x)
                {
                    for (var y = 0; y < image.Height; ++y)
                    {
                        var pixelColor = b.GetPixel(x, y);
                        if (pixelColor.A == 0)
                            continue;
                        
                        if (x < min.X) min.X = x;
                        if (y < min.Y) min.Y = y;

                        if (x > max.X) max.X = x;
                        if (y > max.Y) max.Y = y;
                    }
                }               
                
                var cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X + 1, max.Y - min.Y + 1);

                if (cropRectangle.Width == image.Width && cropRectangle.Height == image.Height)
                    return image;

                return b.Clone(cropRectangle, image.PixelFormat);
            }
        }
    }
}
